package com.light.gamecomponents.physics;

import java.util.ArrayList;

import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.light.gamecomponents.GameForm;

public class RollerPhysicsWorld extends PhysicsWorld {
	
	public enum PhysicsWorldState { RUNNING, PAUSE }
	
	private ArrayList<IUpdateHandler> UpdateList;
	private RollerContactListener contactListener;
	private PhysicsWorldState state = PhysicsWorldState.RUNNING;
	
	public RollerPhysicsWorld(int pStepsPerSecond, Vector2 pGravity, 
			                  boolean pAllowSleep, int pVelocityIterations,
							  int pPositionIterations) 
	{
		super( pGravity, pAllowSleep,
				pVelocityIterations, pPositionIterations);
		
		UpdateList = new ArrayList<IUpdateHandler>();
		contactListener = new RollerContactListener();
		this.setContactListener(contactListener);
	}

	public void registerUpdateHandler(IUpdateHandler handler) { UpdateList.add(handler); }
	public void unregisterUpdateHandler(IUpdateHandler handler) { UpdateList.remove(handler); }
	public void registerContactListener(ContactListener CL) { contactListener.add(CL); }
	public void unregisterContactListener(ContactListener CL) { contactListener.remove(CL); }
	
	@Override
	public void onUpdate(float time)
	{
		if (state == PhysicsWorldState.RUNNING)
		{
			super.onUpdate(time);
			for (int i = 0; i < UpdateList.size(); i++)
				UpdateList.get(i).onUpdate(time);
		}
		else if (state == PhysicsWorldState.PAUSE)
		{
			for (int i = 0; i < UpdateList.size(); i++)
			{
				if (UpdateList.get(i) instanceof GameForm)
					UpdateList.get(i).onUpdate(time);
			}
		}
	}
	
	@Override
	public void reset()
	{
		super.reset();
		UpdateList.clear();
	}
	public void pause()
	{
		state = PhysicsWorldState.PAUSE;
	}
	public void unpause()
	{
		state = PhysicsWorldState.RUNNING;
	}

}
